<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAuthorBooks } from '@/api/user'
import { Search, ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

interface AuthorInfo {
  author: string
  totalBooks: number
}

interface Book {
  bookId: number
  title: string
  categoryName: string
  wordCount: number
  description: string
  publishDate: number
  coverImage: string
}

const authorInfo = ref<AuthorInfo>({
  author: '',
  totalBooks: 0
})

const books = ref<Book[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = 20
const total = ref(0)

const searchText = ref('')

const handleSearch = () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  router.push({
    path: '/user/search-results',
    query: { keyword: searchText.value.trim() }
  })
}

// 获取作者信息和作品列表
const fetchAuthorBooks = async () => {
  loading.value = true
  try {
    const author = route.query.author as string
    if (!author) {
      ElMessage.warning('作者信息不能为空')
      router.push('/')
      return
    }

    const res = await getAuthorBooks({
      author,
      pageNumber: currentPage.value,
      pageSize: pageSize
    })

    if (res.data) {
      books.value = res.data.results
      total.value = res.data.total
      authorInfo.value = {
        author: author,
        totalBooks: res.data.total
      }
    }
  } catch (error) {
    console.error('获取作者作品失败:', error)
    ElMessage.error('获取作者作品失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchAuthorBooks()
}

// 处理图书点击
const handleBookClick = (bookId: number) => {
  router.push({
    path: '/user/book-detail',
    query: { id: bookId }
  })
}

// 格式化日期
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

onMounted(() => {
  fetchAuthorBooks()
})
</script>

<template>
  <div class="author-books-page">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo" @click="router.push('/user/userBook')">
          <img src="https://lovechronicle.oss-cn-zhangjiakou.aliyuncs.com/book.jpg" alt="Library Logo" class="logo-img">
          <span class="logo-text">图书借阅系统</span>
        </div>
      </div>

      <div class="header-center">
        <el-input
          v-model="searchText"
          placeholder="搜索图书..."
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>

      <div class="header-right">
        <el-button class="back-button" @click="router.back()">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
    </el-header>

    <!-- 原有的作者作品内容 -->
    <div class="author-books-container">
      <!-- 作者信息区域 -->
      <div class="author-info">
        <div class="author-header">
          <h1>
            {{ authorInfo.author }}
            <span class="author-tag">本书作者</span>
          </h1>
          <div class="author-stats">
            <div class="stat-item">
              <div class="stat-value">{{ authorInfo.totalBooks }}</div>
              <div class="stat-label">作品数量</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 作品列表 -->
      <div class="books-list" v-loading="loading">
        <template v-if="books.length">
          <div v-for="book in books" :key="book.bookId" class="book-item" @click="handleBookClick(book.bookId)">
            <div class="book-cover">
              <img :src="book.coverImage" :alt="book.title">
            </div>
            <div class="book-info">
              <div class="book-header">
                <h3 class="book-title">{{ book.title }}</h3>
                <span class="category-tag">{{ book.categoryName }}</span>
              </div>
              <div class="book-meta">
                <span class="word-count">{{ book.wordCount }}万字</span>
                <span class="separator">|</span>
                <span class="status">已完结</span>
                <span class="separator">|</span>
                <span class="completion-date">{{ formatDate(book.publishDate) }} 完结</span>
              </div>
              <p class="book-description">{{ book.description }}</p>
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无作品" />

        <!-- 分页器 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :pager-count="7"
            layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange"
            background
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.author-books-page {
  min-height: 100vh;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 70px !important;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  gap: 15px;
  cursor: pointer;
}

.logo-img {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.logo-text {
  font-size: 26px;
  font-weight: 600;
  color: #2c3e50;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.header-center {
  width: 450px;
}

.header-center :deep(.el-input__wrapper) {
  height: 40px;
}

.author-books-container {
  padding-top: 20px;
}

.author-info {
  width: 60%;
  margin: 0 25% 0 auto;
  padding: 40px 30px;
  background-color: rgba(255, 246, 209, 0.6);
  border-radius: 8px;
  position: relative;
}

.author-info::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at top right, rgba(255, 208, 75, 0.2), transparent 60%);
  border-radius: 8px;
  pointer-events: none;
}

.author-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  position: relative;
  z-index: 1;
}

.author-header h1 {
  font-size: 28px;
  color: #333;
  margin: 0;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-tag {
  font-size: 12px;
  padding: 4px 8px;
  background-color: #ffd94c;
  color: #333;
  border-radius: 4px;
  font-weight: normal;
}

.author-stats {
  display: flex;
  justify-content: flex-end;
}

.stat-item {
  text-align: center;
  min-width: 120px;
}

.stat-value {
  font-size: 28px;
  color: #333;
  font-weight: bold;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.books-list {
  width: 60%;
  margin: 20px 25% 0 auto;
  padding: 20px 0;
}

.book-item {
  display: flex;
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.book-cover {
  width: 120px;
  height: 160px;
  margin-right: 20px;
  flex-shrink: 0;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 2px;
  transition: transform 0.3s ease;
}

.book-item:hover .book-cover img {
  transform: scale(1.05);
}

.book-info {
  flex: 1;
}

.book-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.book-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  font-weight: bold;
}

.category-tag {
  padding: 2px 8px;
  background-color: #fff;
  color: #409EFF;
  border: 1px solid #409EFF;
  border-radius: 4px;
  font-size: 12px;
}

.book-meta {
  color: #999;
  font-size: 14px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.separator {
  margin: 0 8px;
  color: #ddd;
}

.book-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.pagination {
  margin: 30px 0;
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-pagination) {
  font-weight: normal;
  font-size: 14px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ffd04b;
  color: #333;
  font-weight: bold;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #ffd04b;
}

:deep(.el-pagination.is-background .el-pager li) {
  margin: 0 4px;
  min-width: 32px;
  border-radius: 4px;
  font-weight: normal;
  background-color: #fff;
}

.header-right {
  display: flex;
  align-items: center;
}

.back-button {
  padding: 8px 16px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: #f5f5f5;
  color: #333;
}
</style> 